<template>
  <!-- :show-file-list="ture" -->
  <div class="upload-img-box">
    <!-- <div v-for="(item,index) in value" :key="index"> -->
    <!-- <img :src="BASE_IMG + item" alt="">
        不晓得为啥，下方直接循环显示图片不行,包了一层后，可以显示了
      -->
    <!-- </div> -->

    <el-button @click="open">选择图片</el-button>
    <div class="choosed-img-list">
      <div v-for="(item, i) in valueAry" :key="item" class="img-box">
        <img v-img-width-height :src="BASE_IMG + item" alt="" class="img">
        <div class="delete-box">
          <svg-icon icon-class="international" class="delete" @click.native="deleteValue(i)"/>
        </div>
      </div>
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      :append-to-body="true"
      class="upload-img-dialog"
      title="选择图片"
      width="800px"
      @closed="closed">
      <el-upload
        :on-success="uploadSuccess"
        :headers="headers"
        :on-change="handleChange"
        :file-list="fileList"
        class="upload-demo"
        action="/api/file/image"
        multiple>
        <el-button size="small" type="primary">本地上传</el-button>
        <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
      </el-upload>
      <div v-loading="loading" class="img-list" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
        <div v-for="(item,index) in imgList" :key="item.id" :class="{choosed: item.choosed}" class="img-item" @click="chooseImg(index)">
          <div class="img-box">
            <img v-img-width-height :src="BASE_IMG + item.url" alt="">
          </div>
          <!-- <el-tooltip class="item" effect="dark" content="dfdgfdfsdfasdasdasdasdasdasdfasd" placement="top-start"> -->
          <div :title="item.name" class="text">
            {{ item.name }}
          </div>
          <!-- </el-tooltip> -->
          <svg-icon icon-class="shopping" class="choosed-icon" />
        </div>
      </div>
      <el-pagination v-show="totalImg > 10" :total="totalImg" layout="prev, pager, next" @current-change="changePage"/>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="sure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import component from "@/"
import { getToken } from '@/utils/auth'
// import { copyObj } from '@/utils'

export default {
  name: 'MlImageUpload',
  components: {},
  props: {
    value: {
      type: null,
      required: true
    },
    limit: {
      type: null,
      required: false,
      default: 1
    }
  },
  data() {
    return {
      headers: {
        'USER-TOKEN': getToken()
      },
      fileList: [],
      totalImg: 0,
      page: 1,
      loading: false,
      dialogVisible: false,
      imgList: [],
      choosedImgList: []
    }
  },
  computed: {
    valueAry() {
      this.initValue()
      return JSON.parse(this.value || '[]')
    }
  },

  created() {},

  mounted() {
    // this.initValue()
    this.getImgList()
  },

  activated() {},

  methods: {
    initValue() {
      // if (Array.isArray(this.value)) {
      this.choosedImgList = JSON.parse(this.value || '[]')
      // }
    },
    // 删除选中的时候，查找当前展示list改变样式
    setCancleChoosed(deleteObj) {
      const deleteIndex = this.imgList.findIndex(obj => obj.url === deleteObj)
      if (deleteIndex > -1) {
        this.imgList[deleteIndex].choosed = false
      }
    },
    // 已选中列表删除图片
    deleteValue(index) {
      const deleteObj = this.choosedImgList.splice(index, 1)
      this.setCancleChoosed(deleteObj[0])
      this.$emit('input', JSON.stringify(this.choosedImgList))
    },
    chooseImg(index) {
      this.imgList[index].choosed = !this.imgList[index].choosed
      const choosedIndex = this.choosedImgList.findIndex(obj => obj === this.imgList[index].url)
      if (this.imgList[index].choosed) {
        if (choosedIndex < 0) {
          this.choosedImgList.push(this.imgList[index].url)
        }
      } else {
        if (choosedIndex > -1) {
          this.choosedImgList.splice(choosedIndex, 1)
        }
      }
      if (this.choosedImgList.length > this.limit) {
        const deleteObj = this.choosedImgList.shift()
        this.setCancleChoosed(deleteObj)
      }
    },
    // 在确定的时候，计算选择的图片
    sure() {
      this.dialogVisible = false
      this.$emit('input', JSON.stringify(this.choosedImgList))
    },
    cancel() {
      this.dialogVisible = false
    },
    closed() {
      this.initValue()
      this.imgList.forEach((obj, index) => {
        if (this.choosedImgList.findIndex(element => element === obj.url) < 0) {
          obj.choosed = false
        } else {
          obj.choosed = true
        }
      })
    },
    uploadSuccess(res, file, fileList) {
      this.getImgList()
      this.$message.success(res.message)
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-1)
    },
    open() {
      this.dialogVisible = true
    },
    changePage(page) {
      this.page = page
      this.getImgList()
    },
    getImgList() {
      this.loading = true
      this.$http.post('file/list', {
        'limit': 10,
        'page': this.page,
        'sort': 'createDate',
        'sortType': 'ASC'
      }).then(res => {
        this.totalImg = res.total
        this.imgList = res.data
        res.data.forEach((obj, index) => {
          this.$set(obj, 'choosed', false)
          // obj.choosed = false
          if (this.choosedImgList && this.choosedImgList.findIndex(element => element === obj.url) >= 0) {
            this.chooseImg(index)
          }
        })
        this.loading = false
      }).catch((err) => {
        console.log(err)
        this.loading = false
        this.$message.error(err)
      })
    }
  }
}
</script>

<style lang='scss' scoped>
.choosed-img-list{
  display: flex;
  flex-wrap: wrap;
  .img-box{
    width: 160px;
    height: 160px;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    position: relative;
    margin: 10px 10px 0 0;
    .img{
      display: block;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    &:hover .delete-box{
      display: block;
    }
    .delete-box{
      display: none;
      position: absolute;
      @include pos(0,0,0,0);
      background: rgba($color: #000000, $alpha: 0.6);
      text-align: right;
      padding: 5px 10px 0 0;
      .delete{
        width: 20px;
        height: 20px;
        color: #ffffff;
        cursor: pointer;
        &:hover{
          color: #409EFF;
        }
      }
    }
  }
}
.upload-img-dialog{
  .upload-demo{
    text-align: right;
  }
  .img-list{
    border-top: 1px solid #e7e7e7;
    margin-top: 10px;
    height: 375px;
    overflow-y: auto;
    padding: 0 20px;
    display: flex;
    flex-wrap: wrap;
    // justify-content: space-around;
    .img-item{
      margin: 20px 0 0 20px;
      width: 120px;
      border: 1px solid #e7e7e7;
      height: 152px;
      border-radius: 4px;
      cursor: pointer;
      // &:first-child{
      //   margin: 20px 0 0 0;
      // }
      &.choosed{
        position: relative;
        &:after{
          content: '';
          width: 100%;
          height: 100%;
          border-radius: 4px;
          position: absolute;
          left: 0;
          top: 0;
          background: rgba($color: #000000, $alpha: 0.7);
        }
        .choosed-icon{
          display: block;
        }
      }
      .choosed-icon{
        display: none;
        position: absolute;
        left: 50%;
        top: 50%;
        width: 60px;
        height: 60px;
        margin-left: -30px;
        margin-top: -30px;
        z-index: 10;
        color: #ffffff;
      }
      .img-box{
        height: 120px;
        overflow: hidden;
        position: relative;
        &>img{
          // width: 100%;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%,-50%);
        }
      }
      .text{
        width: 100%;
        line-height: 30px;
        border-top: 1px solid #e7e7e7;
        padding: 0 5px;
        @include text-overflow;
        // @include inline();
      }
    }
  }
}
</style>
<style lang="scss">
.upload-img-dialog{
  .el-dialog__body{
    padding: 0 20px;
  }
}
</style>

